#include "head.h"
#include <string.h>

int init_dir(const char* name,dir_t* dir){
    dir->name=name;
    dir->child=NULL;
    dir->next=NULL;
    dir->children_count=0;
    return 0;
}
int new_dir(const char* name,dir_t* dir){
    dir_t* pointer;
    dir_t* new=calloc(1,sizeof(dir_t));
    init_dir(name,new);
    if(dir->child==NULL){
        dir->child=new;
        dir->children_count++;
        return 0;
    }
    else{
        pointer=dir->child;
        while(pointer->next!=NULL){
            pointer=pointer->next;
        }
        pointer->next=new;
        dir->children_count++;
        return 0;
    }
}
int remove_dir(const char* name,dir_t* dir){
    if(search_dir(name,dir,0,NULL)==0) return -1;
    else{
        dir_t* pointer=dir->child;
        if(dir->children_count==1){
            free(pointer);
            dir->child=NULL;
            dir->children_count--;
            return 0;
        }
        else{
            while(pointer!=NULL){
                dir_t* pre_pointer=NULL;
                if(strcmp(pointer->name,name)==0){
                    if(pointer==dir->child){
                        dir->child=pointer->next;
                        free(dir->child);
                        return 0;
                    }
                    pre_pointer->next=pointer->next;
                    free(pointer);
                    return 0;
                }
                if(pre_pointer==NULL) pre_pointer=dir->child;
                else pre_pointer=pre_pointer->next;
                pointer=pointer->next;
            }
        }
    }
    return 0;
}
int search_dir(const char* name,dir_t* dir,int mode,char* buf){
    dir_t* pointer=dir->child;
    if(mode==0){
        while(pointer!=NULL){
            if(strcmp(pointer->name,name)==0) return 1;
            pointer=pointer->next;
        }
        return 0;
    }
    else{
        while(pointer!=NULL){
            sprintf(buf,"%s\t",pointer->name);
            pointer=pointer->next;
        }
        return 0;
    }
}
dir_t* move_to_dir(char_stack_t* stack,dir_t* dir){
    if(stack->count==1) return 0;
    char* content=stack->buf;
    int num=stack->count;
    int* arr=stack->start;
    char* pointer;
    char buf[1024];
    int buf_index;
    dir_t* now=dir;
    for(int i=1;i<num;i++){
        int index=arr[i];
        buf_index=0;
        *pointer=content[index];
        if(*pointer=='/'){
            pointer++;
        }
        while(*pointer!='/'&&*pointer!='\0'){
            buf[buf_index++]=*pointer++;
        }
        now=now->child;
        while(strcmp(now->name,buf)!=0) now=now->next;
        bzero(buf,sizeof(buf));
    }
    dir=now;
    return dir;
}
